<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

/**
 * Custom 系统函数库
 */
require_once 'PasswordHash.class.php';

function CheckCoordinate(){
	$address=$_POST['address'];
	$url = "http://api.map.baidu.com/telematics/v3/geocoding?keyWord=$address&cityName=广州市&output=json&out_coord_type=gcj02&ak=UhhXskyMVEOkmbCF4Ggg79BI";
	$str = file_get_contents($url);
	$json = json_decode($str);
    $data['longitude']=$json->results->location->lng;//经度
	$data['latitude']=$json->results->location->lat;//纬度
	return $data;
}

/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[模块/控制器/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $domain 是否显示域名
 * @return string
 */
function leuu($url='',$vars='',$suffix=true,$domain=false){
	$routes=sp_get_routes();
	if(empty($routes)){
		return U($url,$vars,$suffix,$domain);
	}else{
		// 解析URL
		$info   =  parse_url($url);
		$url    =  !empty($info['path'])?$info['path']:ACTION_NAME;
		if(isset($info['fragment'])) { // 解析锚点
			$anchor =   $info['fragment'];
			if(false !== strpos($anchor,'?')) { // 解析参数
				list($anchor,$info['query']) = explode('?',$anchor,2);
			}
			if(false !== strpos($anchor,'@')) { // 解析域名
				list($anchor,$host)    =   explode('@',$anchor, 2);
			}
		}elseif(false !== strpos($url,'@')) { // 解析域名
			list($url,$host)    =   explode('@',$info['path'], 2);
		}

		// 解析子域名
		//TODO?

		// 解析参数
		if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
			parse_str($vars,$vars);
		}elseif(!is_array($vars)){
			$vars = array();
		}
		if(isset($info['query'])) { // 解析地址里面参数 合并到vars
			parse_str($info['query'],$params);
			$vars = array_merge($params,$vars);
		}

		$vars_src=$vars;

		ksort($vars);

		// URL组装
		$depr       =   C('URL_PATHINFO_DEPR');
		$urlCase    =   C('URL_CASE_INSENSITIVE');
		if('/' != $depr) { // 安全替换
			$url    =   str_replace('/',$depr,$url);
		}
		// 解析模块、控制器和操作
		$url        =   trim($url,$depr);
		$path       =   explode($depr,$url);
		$var        =   array();
		$varModule      =   C('VAR_MODULE');
		$varController  =   C('VAR_CONTROLLER');
		$varAction      =   C('VAR_ACTION');
		$var[$varAction]       =   !empty($path)?array_pop($path):ACTION_NAME;
		$var[$varController]   =   !empty($path)?array_pop($path):CONTROLLER_NAME;
		if($maps = C('URL_ACTION_MAP')) {
			if(isset($maps[strtolower($var[$varController])])) {
				$maps    =   $maps[strtolower($var[$varController])];
				if($action = array_search(strtolower($var[$varAction]),$maps)){
					$var[$varAction] = $action;
				}
			}
		}
		if($maps = C('URL_CONTROLLER_MAP')) {
			if($controller = array_search(strtolower($var[$varController]),$maps)){
				$var[$varController] = $controller;
			}
		}
		if($urlCase) {
			$var[$varController]   =   parse_name($var[$varController]);
		}
		$module =   '';

		if(!empty($path)) {
			$var[$varModule]    =   array_pop($path);
		}else{
			if(C('MULTI_MODULE')) {
				if(MODULE_NAME != C('DEFAULT_MODULE') || !C('MODULE_ALLOW_LIST')){
					$var[$varModule]=   MODULE_NAME;
				}
			}
		}
		if($maps = C('URL_MODULE_MAP')) {
			if($_module = array_search(strtolower($var[$varModule]),$maps)){
				$var[$varModule] = $_module;
			}
		}
		if(isset($var[$varModule])){
			$module =   $var[$varModule];
		}

		if(C('URL_MODEL') == 0) { // 普通模式URL转换
			$url        =   __APP__.'?'.http_build_query(array_reverse($var));
				
			if($urlCase){
				$url    =   strtolower($url);
			}
			if(!empty($vars)) {
				$vars   =   http_build_query($vars);
				$url   .=   '&'.$vars;
			}
		}else{ // PATHINFO模式或者兼容URL模式
				
			if(empty($var[C('VAR_MODULE')])){
				$var[C('VAR_MODULE')]=MODULE_NAME;
			}

			$module_controller_action=strtolower(implode($depr,array_reverse($var)));
				
			$has_route=false;
				
			if(isset($routes[$module_controller_action])){
				$urlrules=$routes[$module_controller_action];

				$empty_query_urlrule=array();

				foreach ($urlrules as $ur){
					$intersect=array_intersect($ur['query'], $vars);
					if($intersect){
						$vars=array_diff_key($vars,$ur['query']);
						$url= $ur['url'];
						$has_route=true;
						break;
					}
					if(empty($empty_query_urlrule) && empty($ur['query'])){
						$empty_query_urlrule=$ur;
					}
				}

				if(!empty($empty_query_urlrule)){
					$url=$empty_query_urlrule['url'];
					foreach ($vars as $key =>$value){
						if(strpos($url, ":$key")!==false){
							$url=str_replace(":$key", $value, $url);
							unset($vars[$key]);
						}
					}
					$url=str_replace(array("\d","$"), "", $url);
					$has_route=true;
				}

				if($has_route){
					if(!empty($vars)) { // 添加参数
						foreach ($vars as $var => $val){
							if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
						}
					}
						
					$url =__APP__."/".$url ;
						
				}

					
			}
				
			if(!$has_route){
				$module =   defined('BIND_MODULE') ? '' : $module;
				$url    =   __APP__.'/'.implode($depr,array_reverse($var));
					
				if($urlCase){
					$url    =   strtolower($url);
				}
					
				if(!empty($vars)) { // 添加参数
					foreach ($vars as $var => $val){
						if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
					}
				}
			}
				
				
			if($suffix) {
				$suffix   =  $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
				if($pos = strpos($suffix, '|')){
					$suffix = substr($suffix, 0, $pos);
				}
				if($suffix && '/' != substr($url,-1)){
					$url  .=  '.'.ltrim($suffix,'.');
				}
			}
		}

		if(isset($anchor)){
			$url  .= '#'.$anchor;
		}
		if($domain) {
			$url   =  (is_ssl()?'https://':'http://').$domain.$url;
		}

		return $url;
	}
}

function sp_get_routes($refresh=false){
	$routes=F("routes");

	if( (!empty($routes)||is_array($routes)) && !$refresh){
		return $routes;
	}
	$routes=M("Route")->where("status=1")->order("listorder asc")->select();
	$module_routes=array();
	$cache_routes=array();
	foreach ($routes as $er){
		$full_url=$er['full_url'];
			
		// 解析URL
		$info   =  parse_url($full_url);
			
		$path       =   explode("/",$info['path']);
		if(count($path)!=3){//必须是完整 url
			continue;
		}
			
		$module=strtolower($path[0]);
			
		// 解析参数
		$vars = array();
		if(isset($info['query'])) { // 解析地址里面参数 合并到vars
			parse_str($info['query'],$params);
			$vars = array_merge($params,$vars);
		}
			
		$vars_src=$vars;
			
		ksort($vars);
			
		$path=$info['path'];
			
		$full_url=$path.(empty($vars)?"":"?").http_build_query($vars);
			
		$url=$er['url'];
			
		$cache_routes[$path][]=array("query"=>$vars,"url"=>$url);
			
		$module_routes[$module][$url]=$full_url;
			
	}
	F("routes",$cache_routes);
	$route_dir=SITE_PATH."/data/conf/route/";
	foreach ($module_routes as $module => $routes){

		if(!file_exists($route_dir)){
			mkdir($route_dir);
		}
			
		$route_file=$route_dir."$module.php";
			
		$route_ruels=array();
			
		file_put_contents($route_file, "<?php\treturn " . stripslashes(var_export($routes, true)) . ";");
	}

	return $cache_routes;

}

/**
 * 计算两点之间的距离
 * 
 * @param array $start
 * @param array $end
 * @return string
 */
function getDistance($start, $end){
	$PI = pi();

	$i = ($PI/180);

	$lat1 = $i*$start ['latitude'];
	$lat2 = $i*$end['latitude'];

	$lon1 = $i*$start['longitude'];
	$lon2 = $i*$end['longitude'];

	//地球半径
	$R = 6378;

	//两点间距离 km，如果想要米的话，结果*1000就可以了
	$d =  acos(sin($lat1)*sin($lat2)+cos($lat1)*cos($lat2)*cos($lon2-$lon1))*$R;

	return $d;
}

function getUserLocationByLatAndLong(){
	$latAndLong = getLatAndLongByIp();
	if ($latAndLong) {
		$location = $latAndLong->y.','.$latAndLong->x;
		$params = array(
			'ak' => 'UhhXskyMVEOkmbCF4Ggg79BI',
			'callback' => 'renderReverse',
			'output' => 'json',
			'location' => $location,
		);
		
		$url = 'http://api.map.baidu.com/geocoder/v2/';
		$result = httpGet($url.'?'.http_build_query($params));
		
		$jsonString = substr($result, strpos($result, '(') + 1, -1);
		
		$info = json_decode($jsonString, true);
		if ($info['status'] == 0) {
			return $info['result'];
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function baiduSuggestion($search, $location = false, $region = false) {
	$params = array(
		'ak' => 'UhhXskyMVEOkmbCF4Ggg79BI',
		'query' => $search,
		'output' => 'json',
		'region' => !$region?'全国':$region,
	);
	
	if ($location) {
		$params ['location'] = $location;
	}
	
	$url = 'http://api.map.baidu.com/place/v2/suggestion';
	$jsonString = httpGet($url.'?'.http_build_query($params));
	
	$info = json_decode($jsonString, true);
	if ($info ['status'] == '0') {
		return $info['result'];
	} else {
		return false;
	}
}

/**
 * 获取当前登录的管事员id
 * @return int
 */
function get_current_admin_id(){
	return $_SESSION['ADMIN_ID'];
}

/**
 * 获取当前登录的管事员id
 * @return int
 */
function sp_get_current_admin_id(){
	return get_current_admin_id();
}

/**
 * 检查权限
 * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
 * @param uid  int           认证用户的id
 * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
 * @return boolean           通过验证返回true;失败返回false
 */
function sp_auth_check($uid,$name=null,$relation='or'){
	if(empty($uid)){
		return false;
	}

	$iauth_obj=new \Common\Lib\iAuth();
	if(empty($name)){
		$name=strtolower(MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME);
	}
	return $iauth_obj->check($uid, $name, $relation);
}

/**
 * 替代scan_dir的方法
 * @param string $pattern 检索模式 搜索模式 *.txt,*.doc; (同glog方法)
 * @param int $flags
 */
function sp_scan_dir($pattern,$flags=null){
	$files = array_map('basename',glob($pattern, $flags));
	return $files;
}

/**
 * 给没有后缀的模板文件，添加后缀名
 * @param string $filename_nosuffix
 */
function sp_add_template_file_suffix($filename_nosuffix){



	if(file_exists_case($filename_nosuffix.C('TMPL_TEMPLATE_SUFFIX'))){
		$filename_nosuffix = $filename_nosuffix.C('TMPL_TEMPLATE_SUFFIX');
	}else if(file_exists_case($filename_nosuffix.".php")){
		$filename_nosuffix = $filename_nosuffix.".php";
	}else{
		$filename_nosuffix = $filename_nosuffix.C('TMPL_TEMPLATE_SUFFIX');
	}

	return $filename_nosuffix;
}

function checkPassword($password, $realPassword) {
	$password_cost = C('password_cost');
	$hasher = new \PasswordHash($password_cost, false);
	return $hasher->CheckPassword($password, $realPassword);
}

function hashPassword($password) {
	$password_cost = C('password_cost');
	$hasher = new \PasswordHash($password_cost, false);
	return $hasher->HashPassword($password);
}

function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
	$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

function get_full_url() {
	$https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
	!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
	strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;
	return
	($https ? 'https://' : 'http://').
	(!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
	(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
			($https && $_SERVER['SERVER_PORT'] === 443 ||
					$_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
					substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
}

/**
 * 随机验证码
 * @param unknown $len 生成验证码的长度
 * @return string 一个字串
 */
function randomPhoneCode($len) {
	$codeStr = "0123456789";
	$strLen = strlen($codeStr);
	$codeStr = str_shuffle($codeStr);
	if ($len > $strLen) {
		return substr($codeStr, 0, $strLen);
	}
	
	return substr($codeStr, 0, $len);
}

function weixinToBaidu($lngAndLat) {
	$params = array(
		'ak' => 'iynXFVTGHEpr5LLYTK4Ej4HB',
		'from' => '1',
		'to' => '5',
		'output' => 'json',
		'coords' => $lngAndLat
	);
	$url = 'http://api.map.baidu.com/geoconv/v1/';
	
	$result = httpGet($url.'?'.http_build_query($params));
	$info = json_decode($result, true);
	
	if ($info['status'] == 0) {
		return current($info['result']);
	} else {
		return false;
	}
}

function getLongitudeAndLatitude($address) {
	$params = array(
		'ak' => 'iynXFVTGHEpr5LLYTK4Ej4HB',
		'callback' => 'renderOption',
		'output' => 'json',
		'address' => $address,
	);
	
	$url = 'http://api.map.baidu.com/geocoder/v2/';
	
	$result = httpGet($url.'?'.http_build_query($params));
	
	$jsonString = substr($result, strpos($result, '(') + 1, -1);
	
	$info = json_decode($jsonString);
	if ($info->status == 0) {
		$location = $info->result->location;
		return array (
			'longitude' => $location->lng,
			'latitude' => $location->lat
		);
	} else {
		return false;
	}
}

function httpGet($url) {
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_TIMEOUT, 500);
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	$res = curl_exec($curl);
	
	curl_close($curl);
	return $res;
}

function http_post($url,$post_data){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// post数据
	curl_setopt($ch, CURLOPT_POST, 1);
	// post的变量
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}

function httpsGet($url) {
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($curl, CURLOPT_TIMEOUT, 500);
	curl_setopt($curl, CURLOPT_URL, $url);
	$res = curl_exec($curl);
	curl_close($curl);
	return $res;
}

function https_post($url,$data=null){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	$output = curl_exec($curl);
	curl_close($curl);
	return $output;
}

function https_post_json($url, $jsonStr)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	'Content-Type: application/json; charset=utf-8',
	'Content-Length: ' . strlen($jsonStr)
	)
	);
	$response = curl_exec($ch);
	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

	return array($httpCode, $response);
}